package com.self.structure;

/**
 * 两个栈实现一个队列
 */
public class IQueue {


    private int cap;
    private int size;
    private IStack stack_01;
    private IStack stack_02;

    public IQueue(int cap) {
        this.cap = cap;
        stack_01 = new IStack(cap);
        stack_02 = new IStack(cap);
    }

    public boolean isEmpty() {
        return this.size <= 0;
    }

    public void push(int el) {

        if(this.size == this.cap) {
            throw new RuntimeException("the queue is full");
        }

        if(!stack_02.isEmpty()) {
            transfer(stack_02,stack_01);
        }

        stack_01.push(el);

        this.size++;
    }

    public int pop() {

        if(isEmpty()) {
            throw new RuntimeException("the IStack is empty");
        }

        if(stack_02.isEmpty()) {
            transfer(stack_01,stack_02);
        }

        int v = stack_02.pop();
        this.size--;
        return v;
    }

    private void transfer(IStack from,IStack to) {
        while (!from.isEmpty()) {
            to.push(from.pop());
        }
    }

    public static void main(String[] args) {
        IQueue iQueue = new IQueue(10);
        for (int i=0;i<10;i++) {
            iQueue.push(i);
        }

        while (!iQueue.isEmpty()) {
            System.out.println(iQueue.pop());
        }
    }
}
